/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"
#include "tim.h"
#include "dma.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "nrf24l01.h"
#include "bsp_iic.h"
#include "data.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/*
    通道映射：
    VOL3 ---- PB1 ---- 方向轮
    VOL4 ---- PB2 ---- 油门
    VOL1 ---- PB0 ---- Multi
    VOL2 ---- PA7 ---- 方向微调
    
    SW5 ---- 换挡
    SW1 ---- 
    SW2 ---- 
*/

uint8_t tx_buf[32];
int tx_count=0;
int tx_framerate=0;
int rf_tx_tim_flag=0;
int rf_ch_index=0;

uint16_t start_time;
uint16_t end_time;
uint16_t send_time=0;

uint16_t adc_value[50];

uint16_t channel_value[8];
uint16_t channel_offset[8];
uint16_t channel_output[8];

uint16_t v_bat = 0;

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void led_on(uint8_t n)
{
    if(n==LED_RED)  {
        HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_RESET); 
    }
    else  {
        HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_RESET);        
    }
}
    
void led_off(uint8_t n)
{
    if(n==LED_RED)  {
        HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_SET); 
    }
    else  {
        HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_SET);        
    }
}

void led_control(uint8_t n)
{
    if(n&LED_RED) {
        HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_RESET); 
    }
    else  {
        HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,GPIO_PIN_SET); 
    }
    
    if(n&LED_BLUE) {
        HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_RESET); 
    }
    else  {
        HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,GPIO_PIN_SET); 
    }
}

void led_blink(uint8_t n, uint16_t count, uint16_t time)
{
    int i;
    if(n&LED_RED) {
        led_off(LED_BLUE);
        for(i=0;i<count;i++)
        {
            led_on(LED_RED);
            HAL_Delay(time);
            led_off(LED_RED);
            HAL_Delay(time);
        }
    }
    
    if(n&LED_BLUE) {
        led_off(LED_RED);
        for(i=0;i<count;i++)
        {
            led_on(LED_BLUE);
            HAL_Delay(time);
            led_off(LED_BLUE);
            HAL_Delay(time);
        }
    }
}

void calculate_v_bat(void)
{
    static uint16_t v_bat_last = 0;
    uint16_t v_temp;
    
    v_temp = adc_value[0] * 3300 / 4096; //
    v_bat = (v_temp + (v_bat_last*9))/10;
    v_bat_last = v_bat;
}

void update_channel_data(void)
{
    int i;
    
    channel_offset[0] = adc_value[3]/20;
    
    channel_value[0] = (adc_value[1]/4) + 1000 + channel_offset[0] - 100;
    channel_value[1] = ((4096-adc_value[2])/4) + 1000;
    
    /* 换挡 */
    if(HAL_GPIO_ReadPin(SW5_GPIO_Port,SW5_Pin)==GPIO_PIN_RESET)   {
        channel_value[2] = 2000;
    }
    else  {
        channel_value[2] = 1000;
        
        if(channel_value[1]>1500)
        {
            channel_value[1] = (channel_value[1]-1500) / 2 + 1500;
        }
    }
    
    /* 三段开关 */
    channel_value[3] = 1500;
    if(HAL_GPIO_ReadPin(SW2_GPIO_Port,SW2_Pin)==GPIO_PIN_RESET)   {
        channel_value[3] = 1000;
    }
    if(HAL_GPIO_ReadPin(SW1_GPIO_Port,SW1_Pin)==GPIO_PIN_RESET)   {
        channel_value[3] = 2000;
    }
    
    channel_value[4] = (adc_value[4]/4) + 1000;
    channel_value[5] = ((4096-adc_value[4])/4) + 1000;   
    channel_value[6] = 1500;
    channel_value[7] = 1500;
    
    for(i=0;i<8;i++)
    {
        if(g_ch_rev[i]==0)
        {
            channel_output[i] = channel_value[i];
        }
        else
        {
            channel_output[i] = 3000 - channel_value[i];
        }
    }
    
    for(i=0;i<8;i++)
    {
        tx_buf[4 + (i*2)] = channel_output[i]>>8;
        tx_buf[5 + (i*2)] = channel_output[i]>>0;
    }
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
    uint8_t nrf_check;
    
    HAL_Init();

    SystemClock_Config();

    MX_GPIO_Init();
    MX_DMA_Init();
    MX_ADC1_Init();
    MX_SPI1_Init();
    MX_USART1_UART_Init();
    MX_TIM14_Init();
    
    NRF24L01_Init();    
    
    iic_init();
    
    parameter_load(1);
    
    led_off(LED_BLUE);
    led_on(LED_RED);
    
    HAL_Delay(100);
    nrf_check = NRF24L01_Check();
    if(nrf_check)
    {
        led_control(LED_RED);
    }
    else
    {
        led_control(LED_BLUE);
    }
    
    TIM14->ARR = 2000;
    HAL_TIM_Base_Start_IT(&htim14);
    
    HAL_ADC_Start_DMA(&hadc1, (uint32_t*)adc_value, 5);
    
    /*按住SET键开机，进入参数设置*/
    if(HAL_GPIO_ReadPin(KEY1_GPIO_Port,KEY1_Pin)==0)
    {        
        while(HAL_GPIO_ReadPin(KEY1_GPIO_Port,KEY1_Pin)==0)
        {
            led_blink(LED_RED,1,250);
        }
        
        while(1)
        {
            led_blink(LED_RED,1,500);
            
            update_channel_data();
            if(channel_value[0]<1200)
            {
                g_ch_rev[0] = 0;
                parameter_set(FLASH_ADDR_CH_REV_1,g_ch_rev[0]);  
                led_blink(LED_BLUE,1,250);
                break;                
            }
            if(channel_value[0]>1800)
            {
                g_ch_rev[0] = 1;
                parameter_set(FLASH_ADDR_CH_REV_1,g_ch_rev[0]);  
                led_blink(LED_BLUE,2,250);
                break;
            }
            
            if(channel_value[1]<1200)
            {
                g_ch_rev[1] = 1;
                parameter_set(FLASH_ADDR_CH_REV_2,g_ch_rev[1]);    
                led_blink(LED_BLUE,2,250);                
                break;                
            }
            if(channel_value[1]>1800)
            {
                g_ch_rev[1] = 0;
                parameter_set(FLASH_ADDR_CH_REV_2,g_ch_rev[1]);  
                led_blink(LED_BLUE,1,250);
                break;
            }
        }
        
        led_control(LED_RED);
        
        HAL_Delay(1000);
        NVIC_SystemReset();
    }
    
    while (1)
    {
        if(rf_tx_tim_flag)
        {
            rf_tx_tim_flag = 0;
            
            rf_ch_index++;
            if(rf_ch_index>=10)
            {
                rf_ch_index = 0;
            }
            
            start_time = TIM14->CNT;
            
            NRF24L01_TX_Mode((rf_ch_index * 5) + 1);
            
            tx_count++;
            tx_buf[0] = tx_count>>8;
            tx_buf[1] = tx_count;
            
            update_channel_data();
            
            nrf_check = NRF24L01_TxPacket(tx_buf);
            
            end_time = TIM14->CNT;
            
            if(end_time > start_time)
            {
                send_time = end_time  - start_time;
            }
            
            if(nrf_check == TX_OK)
            {
                led_control(LED_BLUE);
            }
            else
            {
                led_control(LED_RED);
            }
            
            calculate_v_bat();
        }        
    }
}

void main_tick_callback(void)
{
    static int count=0;
    static uint32_t tx_count_last = 0;
    count++;
    if(count>=1000)
    {
        count = 0;
        
        tx_framerate = tx_count - tx_count_last;
        tx_count_last = tx_count;
    }
}
 
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if(htim->Instance == TIM14)
    {        
        rf_tx_tim_flag = 1;
    }
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV1;
  RCC_OscInitStruct.PLL.PLLN = 8;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the peripherals clocks
  */
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1|RCC_PERIPHCLK_ADC;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
  PeriphClkInit.AdcClockSelection = RCC_ADCCLKSOURCE_SYSCLK;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
